#ifndef __TCP_ECHO_SERVER_HPP__
#define __TCP_ECHO_SERVER_HPP__

#include "Comm.hpp"
#include "Logger.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <pthread.h>

static const int gdefaultfd = -1;
static const int gbacklog = 8;
static const uint16_t gport = 8080;

using task_t = std::function<void()>;

class TcpEchoServer
{
private:
    //长任务不适合线程池
    void HandlerIO(int sockfd, InetAddr Client)
    {
        char buffer[1024];
        while (true)
        {
            buffer[0]=0;
            ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n]=0;
                std::string echo_string="srever echo# ";
                echo_string+=buffer;
                LOG(LogLevel::DEBUG)<<Client.ToString()<<" say : "<<buffer;
                write(sockfd,echo_string.c_str(),echo_string.size());

            }
            else if(n==0)
            {
                LOG(LogLevel::INFO)<<"client -"<<Client.ToString()<<" quit"
                <<" me too ,closd fd:"<<sockfd;
                break;
            }
            else 
            {
                LOG(LogLevel::WARNING)<<"read client "<<Client.ToString()<<
                "error sockfd : "<<sockfd;
                break;
            }
            close(sockfd);
        }
    }

public:
    TcpEchoServer(uint16_t port = gport)
        : _port(port)
    {
    }

    void Init()
    {
        // 1.create socket
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "creat tcp _listensockfd error";
            exit(SOCKET_CREATE_ERR);
        }
        LOG(LogLevel::INFO) << "creat tcp _listensockfd seuccess: " << _listensockfd;

        // 2. bind socket
        InetAddr local(_port);

        if (bind(_listensockfd, local.Addr(), local.Length()))
        {
            LOG(LogLevel::FATAL) << "bind _listensockfd error";
            exit(SOCKET_BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind _listensockfd success" << _listensockfd;

        // 3.listen socket
        // 可以用netstat -tlnp命令查看

        if (listen(_listensockfd, gbacklog) != 0)
        {
            LOG(LogLevel::FATAL) << "listen _listensockfd error";
            exit(SOCKET_LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen _listensockfd success";
    }

    //多线程实现
    // class ThreadData
    // {
    //     public:
    //     ThreadData(int sockfd,TcpEchoServer* self,InetAddr client):
    //     _sockfd(sockfd),
    //     _self(self),
    //     _client(client)
    //     {}
    //     public:
    //     int _sockfd;
    //     TcpEchoServer* _self;
    //     InetAddr _client;
    // };

    // static void* Routine(void* arg)
    // {
    //     ThreadData* td=static_cast<ThreadData*>(arg);
    //     pthread_detach(pthread_self());
    //     td->_self->HandlerIO(td->_sockfd,td->_client);

    //     delete td;
    // }

    void Start()
    {
         // signal(SIGCHLD, SIG_IGN); // 最佳实践
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept client error";
                continue;
            }

            InetAddr Clientaddr(peer);
            LOG(LogLevel::INFO) << "获取连接成功,sockfd is:  " << socket << "client addr: " << Clientaddr.ToString();

            // 多进程，多线程
            // 1. 效率问题，创建进程线程
            // 2. 执行流个数没有上限

            // 进程池4:
            ThreadPool<task_t>::GetInstance()->Enqueue([this, sockfd, Clientaddr](){
                this->HandlerIO(sockfd, Clientaddr);
            });

            // handler socket
            // version1 ———单进程
            //HandlerIO(sockfd, Clientaddr);
            
            //version2 --多进程
            //sockfd会被子进程继承
            // pid_t id=fork();
            // if(id<0)
            // {
            //     LOG(LogLevel::FATAL)<<"资源不足，子进程创建失败";
            //     exit(FORK_ERR);
            // }
            // else if(id==0)
            // {
            //     //子进程立马退出->也能看到_listensockfd
            //     close(_listensockfd);
            //     if(fork()>0)
            //     exit(OK);

            //     //孙子进程执行任务，交给系统领养
            //     HandlerIO(sockfd,Clientaddr);
            //     exit(OK);
            // }
            // else{
            //     close(sockfd);//关闭文件描述符，规避fd泄露
            //     //father->sockfd
            //     pid_t rid=waitpid(id,nullptr,0);
            //     (void)rid;
            // }

            //version3 多线程
            // pthread_t tid;
            // ThreadData* td=new ThreadData(sockfd,this,Clientaddr);
            // pthread_create(&tid,nullptr,Routine,(void*)td);
        }
    }

private:
    int _listensockfd; // 监听套接字
    uint16_t _port;
};

#endif